package com.gss.plugin.oauth2.oauth;

import com.gss.plugin.oauth2.config.Oauth2Properties;
import com.gss.plugin.oauth2.exception.OAuth2ResponseExceptionTranslator;
import com.gss.plugin.oauth2.handler.JwtTokenEnhancer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author DYang
 * @date 2023/8/20
 * 授权配置
 */
@ConditionalOnProperty(name = "stars.oauth-token.oauth2",havingValue = "true")
@Configuration
@EnableAuthorizationServer   // 启用授权服务
public class AuthServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private Oauth2Properties oauth2Properties;
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private TokenStore tokenStore;
    @Autowired
    private JwtAccessTokenConverter jwtAccessTokenConverter;
    @Autowired
    private JwtTokenEnhancer jwtTokenEnhancer;
    @Autowired
    private DataSource dataSource;

    private ClientDetailsService clientDetailsService;

    @Autowired
    public void setClientDetailsService(){
        this.clientDetailsService = new JdbcClientDetailsService(dataSource);
    }

    /**
     * 使用密码模式所需配置
     * @param endpoints the endpoints configurer
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        // jwt token增强管理器
        TokenEnhancerChain tokenChain = new TokenEnhancerChain();
        List<TokenEnhancer> enhancerList = new ArrayList<>();
        enhancerList.add(jwtTokenEnhancer);
        enhancerList.add(jwtAccessTokenConverter);
        tokenChain.setTokenEnhancers(enhancerList);

        // 密码模式认证管理器
        endpoints.authenticationManager(authenticationManager);
        // 账号密码认证
        endpoints.userDetailsService(userDetailsService);
        // token 存储方式
        String storeMode = oauth2Properties.getStoreMode();
        if (tokenStore != null) {
            endpoints.tokenStore(tokenStore);
            if ("jwt".equals(storeMode)) {
                endpoints.accessTokenConverter(jwtAccessTokenConverter)
                        .tokenEnhancer(tokenChain);
            }
        }
        // 异常处理
        endpoints.exceptionTranslator(new OAuth2ResponseExceptionTranslator());
    }

    /**
     * 授权配置
     * @param clients the client details configurer
     * @throws Exception
     * 授权请求: http://127.0.0.1:9001/oauth/authorize?response_type=code&client_id=admin&redict_uri=https://www.baidu.com&scopse=all
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.withClientDetails(clientDetailsService);
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security
                .tokenKeyAccess("permitAll()") // 允许访问 /oauth/token_key 公开的密钥端点
                .checkTokenAccess("isAuthenticated()") // 允许访问 /oauth/check_token 检查令牌的端点
                .allowFormAuthenticationForClients() // 允许表单身份验证客户端
                .addTokenEndpointAuthenticationFilter(new CustomCorsFilter());
    }

}
